import { Card, Checkbox, Tag, Dropdown, Button, Space, Slider } from 'antd'
import { TaskItem } from '@/types'
import { taskItemPriorityConfig, taskItemStatusConfig, taskItemTypeConfig } from '../config'
import { DeleteOutlined, DownOutlined, EditOutlined } from '@ant-design/icons'
import React, { useState, useRef, useMemo } from 'react'
import TaskNodeEdit from './TaskNodeEdit'
import { TASK_STATUS } from '@/enums'
import { useTaskStore } from '@/store'
import '../styles/taskCard.css'

/**
 * 有联动的
 * 进度条 & 状态（勾选框）
 *
 **/
/** 递归渲染任务和子任务 */
const TaskNode = ({ task, deleteTask }: { task: TaskItem; deleteTask: (id: string) => void }) => {
  const [isEditing, setIsEditing] = useState(false)
  const [memoProgress, setMemoProgress] = useState(() => (task.progress >= 100 ? 0 : task.progress))
  const isCompleted = useMemo(() => task.status === TASK_STATUS.COMPLETED, [task.status])
  const themeColor = useMemo(() => taskItemTypeConfig[task.type].color, [task.type])

  const cardRef = useRef<HTMLDivElement>(null)
  const { updateTask } = useTaskStore()

  // 状态菜单配置
  const menuProps = {
    items: Object.entries(taskItemStatusConfig).map(([key, value]) => ({
      key,
      label: value.title
    })),
    onClick: (info) => {
      const status = info.key as TASK_STATUS
      let progress = task.progress

      // 根据状态自动设置进度
      if (status === TASK_STATUS.COMPLETED) {
        progress = 100
      } else if (status === TASK_STATUS.NOT_STARTED) {
        progress = 0
      } else if (status === TASK_STATUS.IN_PROGRESS) {
        progress = memoProgress === 100 ? 0 : memoProgress
      }

      updateTask(task.id, { status, progress })
    }
  }

  // 切换任务完成状态
  const handleCheckboxChange = (checked: boolean) => {
    updateTask(task.id, {
      status: checked
        ? TASK_STATUS.COMPLETED
        : memoProgress === 0
          ? TASK_STATUS.NOT_STARTED
          : TASK_STATUS.IN_PROGRESS,
      progress: checked ? 100 : memoProgress
    })
  }

  // 更新进度
  const changeProgress = (value: number) => {
    if (value === task.progress || task.status === TASK_STATUS.COMPLETED) return
    let obj = {}
    if (value <= 0) {
      obj = { status: TASK_STATUS.NOT_STARTED }
    } else if (value >= 100) {
      obj = { status: TASK_STATUS.COMPLETED }
    } else if (value > 0) {
      obj = { status: TASK_STATUS.IN_PROGRESS }
    }
    setMemoProgress(value)
    updateTask(task.id, { ...obj, progress: value })
  }

  // 保存编辑后的任务
  const handleSave = (values: TaskItem) => {
    updateTask(task.id, values)
    setIsEditing(false)
  }

  // 取消编辑
  const handleCancel = () => {
    setIsEditing(false)
  }

  // 编辑模式
  if (isEditing) {
    return <TaskNodeEdit task={task} onSave={handleSave} onCancel={handleCancel} />
  }

  // 查看模式
  return (
    <Card ref={cardRef} className={`card`} size="small" type="inner">
      <div className="flex items-center w-full text-text2 overflow-hidden">
        <Checkbox
          checked={task.status === TASK_STATUS.COMPLETED}
          onChange={(e) => handleCheckboxChange(e.target.checked)}
        />
        <div className="mx-5 min-w-[35%] max-w-[35%] ">
          <div
            className={`title text-xl ${task.status === TASK_STATUS.COMPLETED ? 'line-through text-text3' : ''}`}
          >
            {task.title}
          </div>
          <div
            className="description text-text3 mt-2 w-full"
            style={{
              display: '-webkit-box',
              WebkitLineClamp: 3,
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              wordBreak: 'break-all',
              whiteSpace: 'normal'
            }}
          >
            {task.description}
          </div>
        </div>
        {/* 重要程度标签 */}
        <Tag className="!ml-auto !mr-6" color={taskItemPriorityConfig?.[task?.priority]?.color}>
          {taskItemPriorityConfig?.[task?.priority]?.title}
        </Tag>
        {/* 类型标签 */}
        <Tag color={themeColor}>{taskItemTypeConfig?.[task?.type]?.title}</Tag>
        {/* 进度条 */}
        <div className="ml-4 max-w-[20%] min-w-[20%]">
          <Slider
            value={task.progress}
            min={0}
            max={100}
            trackStyle={{
              backgroundColor: isCompleted ? '#52c41a' : themeColor,
              height: 8,
              borderRadius: 50
            }}
            railStyle={{ backgroundColor: '#f0f0f0', height: 8, borderRadius: 50 }}
            handleStyle={{
              width: 0,
              height: 0,
              opacity: 0
            }}
            onChange={changeProgress}
          />
        </div>

        <div className="ml-6">
          <Dropdown menu={menuProps}>
            <Button color={taskItemStatusConfig?.[task?.status]?.color}>
              <Space>
                {taskItemStatusConfig?.[task?.status]?.title}
                <DownOutlined />
              </Space>
            </Button>
          </Dropdown>
        </div>
        <div className="flex gap-x-2 text-[16px] mx-4">
          <EditOutlined
            className="!text-primary cursor-pointer hover:scale-110"
            onClick={() => setIsEditing(true)}
          />
          <DeleteOutlined
            className="!text-text1 cursor-pointer hover:scale-110"
            onClick={() => deleteTask(task.id)}
          />
        </div>
      </div>
    </Card>
  )
}

export default React.memo(TaskNode)
